const { db, query } = require("../../db/db");
const util = require("util");
const moment = require("moment");
const redisClient = require("../../redis/redisClient.js");

async function LikeArticle(req, res) {
  console.log("输入内容", req.body, req.params);

  let ArticleId = req.body.ArticleId;
  let UserId = Number(req.params.username);
  let CreateTime = moment().format("YYYY-MM-DD HH:mm:ss");

  const userKey = `article:like:users:${ArticleId}`;
  const countKey = `article:like:count:${ArticleId}`;

  const isMember = await redisClient.sismember(userKey, UserId);
  if (isMember) {
    //取消点赞
    await redisClient.srem(userKey, UserId);
    await redisClient.decr(countKey);
    const del_sql = util.format(
      "delete from Article_Like_Info where ArticleId=? and UserId=?"
    );
    db.query(del_sql, [ArticleId, UserId]);
    let likeCount = await redisClient.get(countKey);
    if (likeCount === null) {
      const likeCountSql = util.format(
        "select count(*) as count from Article_Like_Info where ArticleId=%s",
        ArticleId
      );
      const likeCountRes = await query(likeCountSql);
      likeCount = likeCountRes[0]?.count || 0;
      await redisClient.set(countKey, likeCount);
    }
    return res.send({
      Message: "取消点赞成功",
      status: 0,
      likeCount: Number(likeCount),
      isLike: 0,
    });
  }

  await redisClient.sadd(userKey, UserId);
  await redisClient.incr(countKey);

  let likeCount = await redisClient.get(countKey);
  const insert_sql = util.format(
    "insert \
     INTO Article_Like_Info (ArticleId,UserId,CreateTime) \
     Values(?,?,?)"
  );

  db.query(insert_sql, [ArticleId, UserId, CreateTime]);

  res.send({
    Message: "点赞成功",
    status: 0,
    likeCount: Number(likeCount),
    isLike: 1,
  });
}

module.exports = { LikeArticle };
